package com.example.origin.redis.config;

import com.example.origin.redis.utils.ProtoStuffSerializer;
import com.example.origin.redis.utils.SerializerUtil;
import com.example.origin.redis.utils.ZstdBufferedRedisSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Slf4j
@Configuration
public class RedisTemplateConfiguration {
    @Bean
    public <V> RedisTemplate<String, V> defaultRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, V> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setValueSerializer(SerializerUtil.createJackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(SerializerUtil.createJackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public <V> RedisTemplate<String, V> protoStuffRedisTemplate(RedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<String, V> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        ZstdBufferedRedisSerializer<V> protostuff = new ZstdBufferedRedisSerializer<>(new ProtoStuffSerializer<>());
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(protostuff);
        redisTemplate.setHashValueSerializer(protostuff);
        return redisTemplate;
    }

}
